﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Phoenix.Xna.Framework.Properties;

namespace Phoenix.Xna.Framework
{
    public class ServiceCollection : GameServiceContainer, IServiceCollection
    {
        private Dictionary<Type, object> _services = new Dictionary<Type, object>();

        #region GameServiceContainerMembers

        public new void AddService(Type serviceType, object service)
        {
            if (_services.ContainsKey(serviceType))
            {
                throw new ArgumentException(string.Format(Resources.ServicesAlreadyExistsException, serviceType.ToString()));
            }

            _services.Add(serviceType, service);
        }

        public new void RemoveService(Type serviceType)
        {
            if (_services.ContainsKey(serviceType))
            {
                _services.Remove(serviceType);
            }
        }

        #endregion

        #region IServiceCollection Members

        public void AddService<T>(object service)
        {
            Type serviceType = typeof(T);
            AddService(serviceType, service);
        }

        public T GetService<T>()
        {
            Type serviceType = typeof(T);

            if (_services.ContainsKey(serviceType))
            {
                return (T)_services[serviceType];
            }

            return default(T);
        }

        public void RemoveService<T>()
        {
            Type serviceType = typeof(T);
            RemoveService(serviceType);
        }

        public bool ContainsService<T>()
        {
            Type serviceType = typeof(T);
            return _services.ContainsKey(serviceType);
        }

        #endregion

        #region IServiceProvider Members

        public new object GetService(Type serviceType)
        {
            if (_services.ContainsKey(serviceType))
            {
                return _services[serviceType];
            }

            return null;
        }

        #endregion
    }
}
